import asyncio
import websockets
import time
import requests
import json

TCS = [
   'event-topevents',
   'scoreboard-basketball-nba',     # 篮球
   'scoreboard-soccer',             # 足球
]


def bulid_uri():
    url = "http://fastcast.espn.com/public/rotationip"
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
    }
    try:
        resp = requests.get(url, headers=headers)
        sever, token = resp.text.split(',')
        uri = f"ws://{sever}/FastcastService/pubsub/profiles/12000?TrafficManager-Token={token}"
        return uri
    except:
        return ''


def parse_recv(msg):
    return json.loads(msg)


async def start(uri):
    event = TCS[2]
    file = f'espn_recv_{event}.txt'
    async with websockets.connect(uri) as ws:
        await ws.send('{"op":"C"}')
        n = 0
        while True:
            greeting = await ws.recv()
            print(f"↓ {greeting}")
            with open(file, 'a') as f:
                f.write(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] {greeting} \n\n')
            if n == 0:
                greeting= parse_recv(greeting)
                msg = '{"tc":"%s","op":"S","sid":"%s"}' % (event, greeting.get('sid'))
                await ws.send(msg)
                print(f"↑ {msg}")
            if n == 0:
                n += 1

            # break


if __name__ == '__main__':
    
    uri = bulid_uri()
    if uri:
        asyncio.get_event_loop().run_until_complete(start(uri))
